package LearnAlgorithm.f_字符串;

public class h翻转单个字符串但是按照单词 {
	public static void main(String[] args) {
		String string = "Hello World Again";
//		String string = "   ";
		System.out.println(reverseWord(string));
	}
	
	public static String reverseWord(String string) {
		if (string == null || string.length() == 0) {
			return "";
		}
		String[] words = reverseString(string).split("\\s",-1);
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < words.length; i++) {
			if (words[i].equals("")) {
				continue;
			}
			stringBuilder.append(reverseString(words[i]) + " ");//最后一次循环会多加上一个空格
		}
		if (stringBuilder.length() == 0) {
			return "";
		}
		return stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();//删掉多的一个空格再转String
	}
	
	public static String reverseString(String string) {
		if (string == null || string.length() == 0) {
			return "";
		}
		char[] charArr = new char[string.length()];
		for (int i = 0; i < charArr.length; i++) {
			charArr[i] = string.charAt(string.length() - 1 - i);
		}
		return new String(charArr);
	}
}
